const http = require('http')
const fs = require('fs')
const sm = require('sitemap')
const { exec } = require('child_process')
const env = require('../config/env')
const path = require('path')
const fetch = require('node-fetch')
const isProd = process.env.NODE_ENV === 'production'

// const { siteLinksDefault, dayiLinksDefault } = require('../config/staticSitelink')

// 二级导航权重0.7
let secondPriority = ['/cjkj/', '/zjkj/', '/cpa/', '/cta/', '/mat_g/', '/zjjjs/', '/cma/', '/kjsc/']
String.prototype.endWith = function(str) {
  var reg = new RegExp(str + '$')
  return reg.test(this)
}

let siteLinks = []
let dayiLinks = []
let silianLinks = []

const isLocal = env.environment === 'isLocal'

//请求链接内容
async function request(_path, params) {
  let queryArr = []
  let queryString = ''

  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      queryArr.push(`${key}=${value}`)
    })
    queryString = queryArr.join('&')
  }

  const requestParams = queryString ? '?' + queryString : ''
  // const baseUrl = env.serverApiUrl.url + _path
  // 使用正式域名生成sitemap
  // const baseUrl = 'http://edu.zlketang.com' + _path
  const baseUrl = (isProd ? 'http://edu.zlketang.com' : 'http://shenji.zlketang.net') + _path
  const requestUrl = requestParams ? baseUrl + requestParams : baseUrl
  return fetch(requestUrl).then(res => {
    return res.json()
  })
}

// 生成xml URL link
function createXmlUrl(links, name) {
  let date = new Date(),
    compute_date = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
    regularLinks = [],
    priority = 0.5,
    requestLinks = []

  let arr = []

  if (name === 'sitemap.xml') {
    arr = siteLinks
    links.forEach(item => {
      let _path = item.path.includes('/guide') ? item.path + 'Detail' : item.path + '_detail'
      let item_url = _path + (_path.endWith('/') ? '' : '/') + item.id + '.html',
        item_time = item.create_time.split(' ')[0]
      requestLinks.push({
        url: item_url,
        lastmod: item_time,
        priority: 0.5
      })
    })
  }

  if (name === 'sitemap1.xml') {
    arr = dayiLinks
    links.forEach(({ path, create_time }) => {
      requestLinks.push({
        url: path,
        lastmod: create_time,
        priority: 0.5
      })
    })
  }

  // 拼接处理固定链接
  arr.forEach(item => {
    if (item === '/') {
      priority = 1
    } else if (secondPriority.includes(item)) {
      priority = 0.7
    } else {
      priority = 0.5
    }
    regularLinks.push({
      url: item,
      lastmod: compute_date,
      priority: priority
    })
  })
  return [...requestLinks, ...regularLinks]
}
// 生成XML文件
function createXML(links, name = 'sitemap.xml') {
  let urls = createXmlUrl(links, name)
  //这里因为sitemap插件包，会修改urls数据，导致wap生成的链接有问题
  let wapUrls = []
  try {
    wapUrls = JSON.parse(JSON.stringify(urls))
  } catch (e) {}
  const sitemap = sm.createSitemap({
    // js-ignore
    hostname: 'https://www.zlketang.com',
    urls: urls
  })
  if (env.environment !== 'isProd') {
  }
  let fileUrl = `./zl_news_sitemap/sitemap/${name}`
  if (isLocal) {
    fileUrl = path.resolve(__dirname, `../zl_news_sitemap/sitemap/${name}`)
  }
  // 判断是否存在
  if (!fs.existsSync(fileUrl)) {
    console.log(`${name}不存在，创建中...`)
  }
  fs.writeFileSync(fileUrl, sitemap.toString())

  if (name === 'sitemap.xml') {
    const sitemapMobile = sm.createSitemap({
      // js-ignore
      hostname: 'https://wap.zlketang.com',
      urls: wapUrls
    })
    fs.writeFileSync(`./zl_news_sitemap/sitemap/wap_sitemap.xml`, sitemapMobile.toString())
  }
  if (env.environment === 'isProd') {
    // 使用实时生成的sitemap
    // pushSitemapXml()
  }
}

//提交xml到远程仓库
function pushSitemapXml() {
  try {
    exec(`bash ${path.resolve(__dirname, '../hooks/auto-push-xml.sh')}`, err => {
      if (err) {
        console.log('Time:' + parseInt(Date.now() / 1000), 'auto-push-xml failed', err)
      }
    })
  } catch (error) {
    console.log('Time:' + parseInt(Date.now() / 1000), 'pushSitemapXml falied', error)
  }
}

//开始获取 --- 开始时使用
if (env.environment !== 'isProd') {
  // 使用实时生成的sitemap
  requestXML()
}
// 生成死链文件
function requestXML(callback) {
  Promise.all([request('/webapi/api/static_link')])
    .then(res => {
      const adminUrls = res[0]
      // 处理后台配置的链接的默认数据
      if (adminUrls && adminUrls.data && Object.keys(adminUrls.data).length === 3) {
        // 死链
        silianLinks = adminUrls.data[2]
        let fileUrl = `./zl_news_sitemap/sitemap/silian.txt`
        if (Array.isArray(silianLinks)) {
          try {
            if (Array.isArray(silianLinks)) {
              silianLinks = silianLinks.map(item => {
                // js-ignore
                if (!item.includes('www.zlketang.com')) {
                  // js-ignore
                  item = 'https://www.zlketang.com' + item
                }

                return item
              })
              fs.writeFileSync(fileUrl, silianLinks.join('\n'))
            }
          } catch (err) {
            callback && callback({ code: 1, msg: JSON.stringify(err) })
          }
        }
      }
    })
    .catch(err => {
      callback && callback({ code: 1, msg: JSON.stringify(err) })
    })
}

module.exports = {
  requestXML,
  request,
  createXmlUrl
}
